package com.zhoug.chart3.data;

import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.zhoug.chart3.core.styleconfig.IMPPieStyleConfig;
import com.zhoug.chart3.core.styleconfig.MPChartStyleDefaultUtils;
import com.zhoug.chart3.core.styleconfig.MPPieStyleConfig;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * 饼图 数据工厂
 *
 * @Author: zhoug
 * @Date: 2024-02-03
 * @Description:
 */
public class MPPieChartDataCreator {
    private IMPPieStyleConfig styleConfig;
    private OnDateSetCreateListener<PieDataSet> mOnDateSetCreateListener;
    private ValueFormatter mDataSetValueFormatter;

    public MPPieChartDataCreator() {
        this(new MPPieStyleConfig());
    }

    public MPPieChartDataCreator(IMPPieStyleConfig styleConfig) {
        if (styleConfig != null) {
            this.styleConfig = styleConfig;
        } else {
            this.styleConfig = new MPPieStyleConfig();
        }
    }

    public void setStyleConfig(@NonNull IMPPieStyleConfig styleConfig) {
        this.styleConfig = styleConfig;
    }

    public void setDataSetValueFormatter(ValueFormatter dataSetValueFormatter) {
        this.mDataSetValueFormatter = dataSetValueFormatter;
    }

    public void setOnDateSetCreateListener(OnDateSetCreateListener<PieDataSet> onDateSetCreateListener) {
        this.mOnDateSetCreateListener = onDateSetCreateListener;
    }


    /**
     * 创建PieData
     *
     * @param list
     * @param pieKey
     * @return
     */
    public PieData cratePieData(List<HkChartData> list, String pieKey) {
        if (list != null && list.size() > 0) {
            if (pieKey == null) {
                String[] keys = HkChartData.getKeys(list);
                if (keys != null && keys.length > 0) {
                    pieKey = keys[0];
                }
            }
            if (pieKey != null) {
                List<PieEntry> pieEntries = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    HkChartData hkChartData = list.get(i);
                    pieEntries.add(new PieEntry(hkChartData.getValue(pieKey), hkChartData.getName(), hkChartData));
                }
                PieDataSet pieDataSet = new PieDataSet(pieEntries, "");
                pieDataSet.setColors(styleConfig.getPieColors(pieEntries.size()));
                pieDataSet.setValueFormatter(mDataSetValueFormatter);
                MPChartStyleDefaultUtils.initPieDataSet(pieDataSet);
                if(mOnDateSetCreateListener!=null){
                    mOnDateSetCreateListener.onInitDataSetStyle(pieDataSet,0);
                }
                PieData pieData = new PieData(pieDataSet);
                return pieData;
            }
        }
        return null;
    }


}
